const clearCache = async () => {
    await caches.delete('m3u8-online');
}

const putInCache = async (request, response) => {
    const cache = await caches.open('m3u8-online');
    await cache.put(request, response);
};

const cacheFirst = async (request) => {
    const responseFromCache = await caches.match(request);
    if (responseFromCache) {
        return responseFromCache;
    }

    try {
        const responseFromNetwork = await fetch(request.clone());
        putInCache(request, responseFromNetwork.clone());
        return responseFromNetwork;
    } catch {
        return new Response(undefined, { status: 408 });
    }
};

self.addEventListener('message', (e) => {
    if (e.data.command === "clearCache") {
        clearCache();
    }
});

self.addEventListener('fetch', (e) => {
    if (e.request.url.endsWith(".ts") || e.request.url.includes(".m3u8")) {
        e.respondWith(
            cacheFirst(e.request)
        );
    }
});